package cn.com.shbs.Controller;

import cn.com.shbs.Config.CommonUtil;
import cn.com.shbs.Config.Page;
import cn.com.shbs.Dao.BaseNcard.BaseNcardDao;
import cn.com.shbs.Dao.BaseNcardSerive.BaseNcardSeriveDao;
import cn.com.shbs.Dao.ClassLevel.ClassLevelDao;
import cn.com.shbs.Dao.Customer.CustomerDao;
import cn.com.shbs.Dao.UserInfoDao.UserInfoDao;
import cn.com.shbs.model.*;
import cn.com.shbs.Service.NCardService.INcardService;
import cn.com.shbs.Service.code.SerialNumberGeneratorService;
import cn.com.shbs.model.BaseNcard;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.tools.java.Parser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("API/")
public class NCardServiceController {
    static Logger logger = LoggerFactory.getLogger(NCardServiceController.class);

    @Autowired
    ClassLevelDao classLevelDao;
    @Autowired
    SerialNumberGeneratorService serialNumberGeneratorService;
    @Autowired
    INcardService iNcardService;
    @Autowired
    UserInfoDao userInfoDao;

    @Autowired
    BaseNcardDao baseNcardDao;
    @Autowired
    BaseNcardSeriveDao baseNcardSeriveDao;
    @Autowired
    CustomerDao customerDao;
    //查询分类
    @RequestMapping("/selectClassify")
    public Object selectClassify(HttpServletRequest request,
                                 HttpServletResponse response,
                                 @RequestParam(value="class_code",required=false)String class_code){

        logger.info("NCardServiceController.selectClassify() 方法start");
        String message = "success";
        JSONObject result=new JSONObject();
        List<HashMap> serviceList =new ArrayList<>();
        HashMap<String,Object> map=new HashMap<>();
        try{
            map.put("class_code",class_code);
            serviceList=classLevelDao.selectClassify(map);
        }catch (Exception e){
            message = "error";
            logger.error("NCardServiceController.selectClassify()",e);
            e.printStackTrace();
        }

        logger.info("NCardServiceController.selectClassify() 方法end");
        result.put("serviceList", JSONArray.fromObject(serviceList));

        result.put("message",message);
        return result.toString();

    }

    /**
     * 按要求查询项目
     * @param request
     * @param response
     * @param page
     * @param class_code 分类code
     * @param servicename 服务名称
     * @return
     */
    @RequestMapping("/queryClassService")
    public Object queryClassService(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Page page,
                                    @RequestParam(value="class_code",required=false)String class_code,
                                    @RequestParam(value="servicename",required=false)String servicename){
        logger.info("NCardServiceController.queryClassService() 方法start");
        String message = "success";
        JSONObject result=new JSONObject();
        HashMap<String,Object> servicemap=new HashMap<>();

        List<HashMap> serviceList =new ArrayList<>();

        //总条数
        int countnum=0;
        try {
            //参数
            servicemap.put("class_code",class_code);
            servicemap.put("servicename",servicename);

            //查询符合条件的总条数
            countnum = classLevelDao.queryServiceNum(servicemap);
            //总条数
            page.setTotalCount(countnum);

            servicemap.put("startIndex",page.getStartCount());

            servicemap.put("pageSize", page.getPageSize());

            //通过参数map查询顾客list
            serviceList = classLevelDao.queryService(servicemap);

        }catch (Exception e){
            message = "error";
            logger.error("NCardServiceController.queryClassService()",e);
            e.printStackTrace();
        }
        logger.info("NCardServiceController.queryClassService() 方法end");
        result.put("serviceList", JSONArray.fromObject(serviceList));
        result.put("page", JSONObject.fromObject(page));
        result.put("message",message);
        return result.toString();
    }

    /**
     *查询次卡
     * @param request
     * @param response
     * @param page
     * @param name
     * @param state
     * @return
     */

    @RequestMapping("/queryNCardlist")
    public Object queryNCardlist(HttpServletRequest request,
                                    HttpServletResponse response,
                                    Page page,
                                    @RequestParam(value="name",required=false)String name,
                                    @RequestParam(value="state",required=false)String state){
        String message = "success";
        JSONObject result=new JSONObject();
        HashMap<String,Object> servicemap=new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        //取身份信息
        LoginUser userInfo = (LoginUser) subject.getPrincipal();
        //总条数
        List <HashMap>  baseNcardList = new ArrayList<>();
        int countnum=0;
        try {

            servicemap.put("name",name);
            servicemap.put("state",state);
            servicemap.put("storecode",userInfo.getBelong_store());
            //查询符合条件的总条数
            countnum = baseNcardDao.queryNCardlisttotal(servicemap);
            //总条数
            page.setTotalCount(countnum);
            servicemap.put("startIndex",page.getStartCount());

            servicemap.put("pageSize", page.getPageSize());

            baseNcardList= baseNcardDao.queryNCardlist(servicemap);

            result.put("baseNcardList",JSONArray.fromObject(baseNcardList));

        }catch (Exception e){
            e.printStackTrace();
            logger.error("NCardServiceController.queryNCardlist()",e);
        }
        result.put("page", JSONObject.fromObject(page));
        result.put("message",message);
        return result.toString();

    }




    /**
     * 添加次卡基本信息，次卡基本服务信息
     * @param request
     * @param response
     * @param baseNcard
     * @param basecardJson
     * @return
     */
    @RequestMapping("/insertNcard")
    public Object insertNcard(HttpServletRequest request,
                                    HttpServletResponse response,
                              BaseNcard baseNcard,
                              @RequestParam(value="basecardJson")String basecardJson){
        logger.info("NCardServiceController.insertNcard() 方法start");
        String message = "success";
        JSONObject result=new JSONObject();
        HashMap<String,Object> servicemap=new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        //取身份信息
        LoginUser userInfo = (LoginUser) subject.getPrincipal();

        List<HashMap> serviceList =new ArrayList<>();
        List<BaseNcardSerive> ncardSeriveList =new ArrayList<>();

        try {
            if(baseNcard.getBase_ncard_name()==null||"".equals(baseNcard.getBase_ncard_name().trim())){
                //次卡名称为空
                message="nameisnull";
                result.put("message",message);
                return result.toString();
            }
            //生成次卡服务id
            String baseNcardCode=  CommonUtil.PREFIX_BASENCARD+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.NCARD_TYPE);
           //设置次卡code
            baseNcard.setBase_ncard_code(baseNcardCode);
            //设置次卡停用状态
            //baseNcard.setBase_ncard_state("正常");
            //设置创建时间
            baseNcard.setCreattime(CommonUtil.getNowTime_tamp());
            //设置次卡所属店铺
            baseNcard.setBase_ncard_store_code(userInfo.getBelong_store());
            /**
             * 次卡服务
             */
            JSONArray array=JSONArray.fromObject(basecardJson);
            if(array.size()>0){
                for(int i=0;i<array.size();i++){
                    BaseNcardSerive cardserive= CommonUtil.JSON2Object(array.getString(i));
                    //生成次卡服务id
                    String baseNcardServiceCode=  CommonUtil.PREFIX_NCARDSERVICE+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.NCARDSERVICE_TYPE);
                    //设置此卡服务code
                    cardserive.setBase_ncard_serive_code(baseNcardServiceCode);
                    //设置此卡服务关联次卡code
                    cardserive.setBase_ncard_code(baseNcardCode);

                    ncardSeriveList.add(cardserive);
                }

                iNcardService.insertNcard(baseNcard,ncardSeriveList);

            }


        }catch (Exception e){
            message = "error";
            logger.error("NCardServiceController.insertNcard()",e);
            e.printStackTrace();
        }
        logger.info("NCardServiceController.insertNcard() 方法end");
        result.put("ncardSeriveList", JSONArray.fromObject(ncardSeriveList));
        result.put("baseNcard", JSONObject.fromObject(baseNcard));
        result.put("message",message);
        return result.toString();
    }


    /**
     * 修改次卡状态
     * @param request
     * @param response
     * @param base_ncard_code 次卡code
     * @param base_ncard_state 次卡状态
     * @return
     */
    @RequestMapping("/updateNcard")
    public Object updateNcard(HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam(value="base_ncard_code",required = false)String base_ncard_code,
                              @RequestParam(value="base_ncard_state",required = false)String base_ncard_state){
        logger.info("NCardServiceController.updateNcard() 方法start");
        String message = "success";
        JSONObject result=new JSONObject();
        HashMap<String,Object> servicemap=new HashMap<>();


        try {
            servicemap.put("base_ncard_code",base_ncard_code);
            servicemap.put("base_ncard_state",base_ncard_state);
            baseNcardDao.updateNcard(servicemap);
        }catch (Exception e){
            message = "error";
            logger.error("NCardServiceController.updateNcard()",e);
            e.printStackTrace();
        }
        logger.info("NCardServiceController.updateNcard() 方法end");
        result.put("message",message);
        return result.toString();
    }


    /**
     *
     * @param request
     * @param response
     * @param NcardPurchase
     * @param peoplejson
     * @return
     */
    /**
     * 购买次卡
     * @param request
     * @param response
     * @param pay_balance 🈷️余额支付金额
     * @param pay_cash 现金支付金额
     * @param customer_code 客户code
     * @param peoplejson 服务人员code以，隔开
     * @param cardcode 次卡code
     * @return
     */
    @RequestMapping("/buyNcard")
    public Object buyNcard(HttpServletRequest request,
                              HttpServletResponse response,

                           @RequestParam(value="pay_balance",required = false)String pay_balance,
                           @RequestParam(value="pay_cash",required = false)String pay_cash,
                           @RequestParam(value="customer_code",required = false)String customer_code,
                              @RequestParam(value="peoplejson",required = false)String peoplejson,
                           @RequestParam(value="cardcode",required = false)String cardcode
                           ){
        logger.info("NCardServiceController.buyNcard() 方法start");
        String message = "success";
        JSONObject result=new JSONObject();
        HashMap<String,Object> servicemap=new HashMap<>();
        Subject subject = SecurityUtils.getSubject();
        //取身份信息
        LoginUser userInfo = (LoginUser) subject.getPrincipal();


        try {
            String pay_method=null;

            /**
             * 判断支付方式
             */
            if(Double.parseDouble(pay_balance)==0 && Double.parseDouble(pay_cash)!=0){
                pay_method="现金";
            }else if(Double.parseDouble(pay_balance)!=0 && Double.parseDouble(pay_cash)==0){
                pay_method="会员卡余额支付";
            }else{
                pay_method="现金支付:"+pay_cash+"元，余额支付"+pay_balance+"元";
            }

            /**
             * 如果余额支付查询余额是否足够
             */
            if(Double.parseDouble(pay_balance)!=0){

                //int num= customerDao.queryBalance(codcustomer_codee);
            }
            //次卡项目记录
            List<NcardService> ncardServicelist=new ArrayList<>();
            //流水表
            AccountStatement accountStatement=new AccountStatement();
            //服务人员表-提成表
            List<ServicePeoples> servicePeopleslist=new ArrayList<>();

            NcardPurchase NcardPurchase=new NcardPurchase();



            /**
             * 1:先判断支付方式；
             * 1）如果是现金支付，添加次卡购买记录表，次卡项目记录。流水表；
             * 2）如果是会员余额支付，判断会员余额是否足够支付；
             * 3）会员足够支付，减会员余额；添加服务人员表-提成表  service_peoples
             *
             */

            if(pay_method==null
                    ||"".equals(pay_method.trim())){
                //支付方式为空
                message="payisnull";
                result.put("message",message);
                return result.toString();
            }
            //根据次卡code查询次卡
            BaseNcard card=baseNcardDao.querybaseNcard(cardcode);

            /**
             * 次卡购买记录赋值
             */
            String code=CommonUtil.PREFIX_NCARDPURCHASE+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.NCARDPURCHASE_TYPE);

            NcardPurchase.setPurchase_code(code);

            //设置创建者
            NcardPurchase.setCreateid(userInfo.getUser_code());

            //创建时间
            NcardPurchase.setCreatime(CommonUtil.getNowTime_tamp());

            //顾客code
            NcardPurchase.setCustomer_code(customer_code);

            //
            NcardPurchase.setDeleteflag("0");

            //此卡名称
            NcardPurchase.setNcard_name(card.getBase_ncard_name());

            //设置支付方式
            NcardPurchase.setPay_method(pay_method);

            //设置所属店铺
            NcardPurchase.setStore_code(userInfo.getBelong_store());

            //设置价格
            NcardPurchase.setTotal_price(card.getBase_ncard_price());



            /**
             *流水表赋值
             */
            String accountCode=CommonUtil.PREFIX_ACCOUNT+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.ACCOUNT_TYPE);

            //流水code
            accountStatement.setAccount_statement_code(accountCode);

            //商品名称
            accountStatement.setAccount_name(NcardPurchase.getNcard_name());

            //金额
            accountStatement.setPrice(NcardPurchase.getTotal_price());

            //创建时间
            accountStatement.setCreatime(CommonUtil.getNowTime_tamp());

            //创建者
            accountStatement.setCreateid(userInfo.getUser_code());

            //消费者
            accountStatement.setCustomer_code(NcardPurchase.getCustomer_code());

            //支付方式
            accountStatement.setPayment_method(NcardPurchase.getPay_method());

            //备注
            accountStatement.setRemarks("");

            //消费类别
            accountStatement.setConsume_type("次卡购买");

            //相关订单ID
            accountStatement.setOrder_code(NcardPurchase.getPurchase_code());

            /**
             *次卡项目记录
             */
            //根据次卡code查询次卡包含的服务项目
            List<BaseNcardSerive> cardlist=new ArrayList<>();
            cardlist=baseNcardSeriveDao.queryCardService(cardcode);

            if(cardlist.size()>0){
                for(BaseNcardSerive basencardSerive:cardlist){
                    String NSCode=CommonUtil.PREFIX_NCARD+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.NCARDSER_TYPE);
                    NcardService ncardService=new NcardService();
                    //设置次卡项目记录code
                    ncardService.setNcard_service_code(NSCode);
                    //设置项目名称
                    ncardService.setProduct_name(basencardSerive.getService_name());
                    //设置数量
                    ncardService.setProduct_num(basencardSerive.getBase_ncard_num());
                    //关联次卡购买记录 code
                    ncardService.setNcard_purchase_code(code);
                    //价格
                    ncardService.setBase_ncard_serive_price(basencardSerive.getBase_ncard_serive_price());

                    ncardServicelist.add(ncardService);
                }
            }

            /**
             * 提成比率
             */
            JSONArray array=JSONArray.fromObject(peoplejson);
            if(array.size()>0){
                for(int i=0;i<array.size();i++){
                    ServicePeoples servicePeoples=new ServicePeoples();
                    String servicecode=CommonUtil.PREFIX_SERVICEPEOPLE+serialNumberGeneratorService.getCodeGeneratorstr(CommonUtil.STEPNUM,CommonUtil.SERVICEPEOPLE_TYPE);
                    String rate= userInfoDao.queryRate(array.getString(i));

                    //相关购买记录code
                    servicePeoples.setLooks_service_code(code);
                    //创建者
                    servicePeoples.setCreatid(userInfo.getUser_code());
                    //提成金额
                    servicePeoples.setRoyalty_price(NcardPurchase.getTotal_price()*Double.parseDouble(rate));
                    //
                    servicePeoples.setService_peoples_code(servicecode);
                    //提成比例
                    servicePeoples.setRoyalty_rate(rate);
                    //购买记录类别
                    servicePeoples.setService_type("购买次卡");
                    servicePeoples.setUser_code(array.getString(i));
                    servicePeopleslist.add(servicePeoples);
                }
            }
            if("会员卡余额".equals(pay_method.trim())){



            }


        }catch (Exception e){
            message = "error";
            logger.error("NCardServiceController.buyNcard()",e);
            e.printStackTrace();
        }
        logger.info("NCardServiceController.buyNcard() 方法end");
        result.put("message",message);
        return result.toString();
    }
}
